<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="临近区县分析" data-page-identification="z_c06tfrygrs">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_alrw8ri7qx 面包屑_826y6allnc -->
            <a-breadcrumb class="vid_alrw8ri7qx" style="word-break: break-word">
                <a-breadcrumb-item
                    v-for="(item, index) in vid_alrw8ri7qx_props_tabConfig"
                    :key="index"
                    @click="handleBreadcrumbJump(router, item)"
                    href=""
                >
                    <template v-if="vid_alrw8ri7qx_props.rt_showIcon">
                        <span v-if="/^(https?:|mailto:|tel:|data:image)/.test(item.icon)" role="img" class="anticon"
                            ><embed style="width: 1em; height: 1em" :src="item.icon"
                        /></span>
                        <component v-else :is="item.icon" />
                    </template>
                    {{ item.title }}
                </a-breadcrumb-item>
            </a-breadcrumb>
            <!-- end vid_alrw8ri7qx 面包屑_826y6allnc -->
            <!-- begin vid_x5evdsd5xf 自定义模板_x6epeaj6d6 -->
            <div class="body">
                <div class="top-search">
                    <div>
                        <a-row :gutter="24">
                            <a-col :span="5">
                                <a-form-item label="区域选择" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }">
                                    <a-tree-select
                                        v-model:value="state.regionName"
                                        show-search
                                        style="width: 100%"
                                        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                        placeholder="请选择区域"
                                        :allow-clear="false"
                                        tree-default-expand-all
                                        :tree-data="state.countryTreeList"
                                        tree-node-filter-prop="name"
                                        :field-names="{
                                            children: 'children',
                                            label: 'name',
                                            value: 'id'
                                        }"
                                        @focus="getCountryTreeList(false)"
                                        @change="regionChange"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </div>
                </div>
                <a-spin :spinning="state.spinng" tip="加载中">
                    <div class="content">
                        <div class="top-chart">
                            <div class="left">
                                <div class="content-title">
                                    <div class="tip">
                                        <div class="tip-msg">{{ state.regionTitle }}临近区县水泥平均到位价格分析</div>
                                    </div>
                                </div>
                                <div ref="chartContainer" class="chart"> </div>
                            </div>
                            <div class="right">
                                <div class="content-title">
                                    <div class="tip">
                                        <div class="tip-msg">{{ state.regionTitle }}临近区县水泥平均到位价格差分析</div>
                                    </div>
                                </div>
                                <div ref="rightContauner" class="chart"></div>
                            </div>
                        </div>
                        <div class="default-table">
                            <a-table
                                :scroll="{ y: 200 }"
                                :columns="columns"
                                :data-source="state.tableData"
                                bordered
                                :loading="state.spinng"
                                :pagination="false"
                            >
                                <template #bodyCell="{ column, record, text, index }">
                                    <template
                                        v-if="
                                            column.dataIndex === 'inplacePriceDifference' ||
                                            column.dataIndex === 'yearInplacePriceDifference'
                                        "
                                    >
                                        <span v-if="text == 0">--</span>
                                        <span v-else>{{ text }}</span>
                                    </template>
                                    <template v-if="column.dataIndex === 'count'">
                                        {{ index + 1 }}
                                    </template>
                                    <template v-if="column.dataIndex === 'opration'">
                                        <a-space>
                                            <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                                            <a-popconfirm @confirm="handleDelete(record)" title="确定删除吗？">
                                                <a-button type="link">删除</a-button>
                                            </a-popconfirm>
                                        </a-space>
                                    </template>
                                </template>
                            </a-table>
                        </div>
                    </div>
                </a-spin>
            </div>
            <!-- end vid_x5evdsd5xf 自定义模板_x6epeaj6d6 -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    const vid_alrw8ri7qx_props = reactive({
        rt_showIcon: false
    })

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */
    const vid_alrw8ri7qx_props_tabConfig = computed(() => {
        const initValue = [
            {
                'key': 'tab1',
                'title': '数据分析',
                'targetPage': { 'settingType': '', 'url': '', 'customUrl': '' },
                'icon': '',
                'parameter': [],
                'applicationId': 3000000036,
                'query': {}
            },
            {
                'key': 'tab2',
                'title': '临近区县价差分析',
                'icon': '',
                'targetPage': { 'settingType': '', 'url': '', 'customUrl': '' },
                'parameter': [],
                'applicationId': 3000000036,
                'query': {}
            }
        ]
        return initValue
    })
    /*** PUBLISH_EXEGESIS ***
 systemStore.addBreadcrumbInfo(vid_alrw8ri7qx_props_tabConfig.value);
 *** PUBLISH_EXEGESIS ***/
    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import { nextTick } from 'vue'
    import * as echarts from 'echarts'
    // 定制化逻辑
    const state = reactive({
        firstId: undefined,
        regionName: undefined,
        countryTreeList: [],
        regionTitle: '',
        dynamicData: [],
        tableData: [],
        spinng: false,
        urlRegionId: undefined,
        urlProviceId: undefined
    })
    const findIdByName = (data, targetName) => {
        for (const item of data) {
            if (item.name === targetName) {
                return item.id
            }
            if (item.children && item.children.length > 0) {
                const result = findIdByName(item.children, targetName)
                if (result) return result
            }
        }
        return null // 如果未找到，返回 null
    }
    function getCountryTreeList(flag) {
        get('/dynamic-price/api/v1/near_country_price/tree').then(data => {
            if (data.status !== 'success') {
                message.error(data.errorMsg)
                return
            }
            state.countryTreeList = data.data
            let firstId = findFirstLeafNode(state.countryTreeList)
            const id = findIdByName(state.countryTreeList, '农安县')
            if (flag) {
                state.regionName = id
                getData()
            }
        })
    }
    function getData() {
        state.spinng = true
        post('/dynamic-price/api/v1/near_country_price/analysis', {
            areaId: state.regionName ? state.regionName : null,
            areaName: findNameById(state.regionName, state.countryTreeList)
                ? findNameById(state.regionName, state.countryTreeList)
                : null
        })
            .then(data => {
                if (data.status !== 'success') {
                    message.error(data.errorMsg)
                    return
                }
                state.dynamicData = data.data.nearCountryPriceList
                state.tableData = data.data.nearCountryPriceTableList
                let name = findNameById(state.regionName, state.countryTreeList)
                state.regionTitle = `${name}`
                // if (state.dynamicData.length > 0) {
                renderChart()
                // }
            })
            .finally(() => {
                state.spinng = false
            })
    }
    const chartContainer = ref(null)
    const rightContauner = ref(null)
    let myChart = null
    let rightChart = null

    function findNameById(id, data) {
        for (const item of data) {
            if (item.id === id) {
                return item.name
            }
            if (item.children && item.children.length) {
                const foundName = findNameById(id, item.children)
                if (foundName) {
                    return foundName
                }
            }
        }
        return null // 如果没有找到，返回 null
    }
    // 找第一个默认选中
    function findFirstLeafNode(treeData) {
        for (let node of treeData) {
            if (!node.children || node.children.length === 0) {
                return node // 当前节点是叶子节点，返回
            } else {
                // 递归查找子节点
                const leafNode = findFirstLeafNode(node.children)
                if (leafNode) {
                    return leafNode
                }
            }
        }
        return null // 如果没有找到叶子节点
    }
    function regionChange() {
        let name = findNameById(state.regionName, state.countryTreeList)
        state.regionTitle = `${name}-`
        getData()
    }
    // 预设的 8 种颜色
    const colors = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4']

    // 函数：根据动态数据生成 x 轴和 series 数据
    const getOptionFromData = data => {
        const xAxisData = data.map(item => item.areaName)
        const seriesData = data.map(item => ({
            value: item.yearInplacePrice,
            itemStyle: { color: '#5470C6' }
        }))
        const seriesData1 = data.map(item => ({
            value: item.inplacePrice,
            itemStyle: { color: '#91CC75' }
        }))
        const averagePrice = data[0].ownerInplacePrice || 0
        const price2 = data[0].ownerYearInplacePrice || 0

        return {
            xAxis: {
                type: 'category',
                data: xAxisData,
                axisLabel: { interval: 0, rotate: 25 }
            },
            yAxis: {
                name: '到位价:元/吨',
                nameTextStyle: { color: '#aaa', nameLocation: 'start' },
                type: 'value'
            },
            grid: {
                right: '15%'
            },
            series: [
                {
                    name: '历史到位价',
                    type: 'bar',
                    data: seriesData,
                    emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.3)' } },
                    barWidth: '20px'
                },
                {
                    name: '实时到位价',
                    type: 'bar',
                    data: seriesData1,
                    emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.3)' } },
                    barWidth: '20px'
                },
                {
                    type: 'line',
                    data: [],
                    markLine: {
                        data: [
                            {
                                name: '平均价格',
                                yAxis: averagePrice,
                                symbol: 'none',
                                lineStyle: { type: 'dashed', color: '#3875ff', width: 1 }
                            }
                        ],
                        label: {
                            position: 'end',
                            formatter: function () {
                                return [
                                    `{a|${state.regionTitle}\n实时到位价:￥${averagePrice}}`,
                                    `{b|历史到位价:￥${price2}}`
                                ].join('\n')
                            },
                            rich: {
                                a: {
                                    align: 'center',
                                    padding: [5, 0],
                                    color: '#000'
                                },
                                b: {
                                    align: 'center',
                                    padding: [5, 0],
                                    color: '#000'
                                }
                            }
                        }
                    }
                }
            ],
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' }
            },
            legend: {
                icon: 'rect',
                data: ['历史到位价', '实时到位价'],
                itemWidth: 20,
                itemHeight: 10,
                itemGap: 30
            }
        }
    }

    const getRightOptionFromData = data => {
        const xAxisData = data.map(item => item.areaName) // 将 name 映射到 x 轴
        const seriesData = data.map((item, index) => ({
            value: item.yearInplacePriceDifference,
            itemStyle: {
                color: '#5470C6' // 循环为每个柱子分配颜色
            }
        }))
        const seriesData1 = data.map((item, index) => ({
            value: item.inplacePriceDifference,
            itemStyle: {
                color: '#91CC75' // 循环为每个柱子分配颜色
            }
        }))

        return {
            xAxis: {
                type: 'category',
                data: xAxisData, // x 轴数据
                axisLabel: {
                    interval: 0, // 强制显示所有标签
                    rotate: 25 // 旋转45度
                }
            },
            legend: {
                icon: 'rect',
                data: ['历史到位价差值', '实时到位价差值'],
                itemWidth: 20, // 设置宽度
                itemHeight: 10, // 设置高度
                itemGap: 30 // 设置间距
            },
            yAxis: {
                name: '价差:元/吨',
                nameTextStyle: {
                    color: '#aaa',
                    nameLocation: 'start'
                },
                type: 'value'
            },
            series: [
                {
                    name: '历史到位价差值',
                    nameLocation: 'end', // 单位的位置，放在轴的末端
                    type: 'bar',
                    data: seriesData, // y 轴数据
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0,0,0,0.3)'
                        }
                    },
                    barWidth: '20px',
                    label: {
                        show: true,
                        position: 'top',
                        formatter: params => {
                            const diffClass = params.value > 0 ? 'positive' : 'negative'
                            return ` {${diffClass}|${params.value}}`
                        },
                        rich: {
                            a: { color: '#000' }, // 默认的文本颜色
                            positive: { color: 'green' }, // 正数的颜色
                            negative: { color: 'red' } // 负数的颜色
                        }
                    }
                    // barGap: '100%',
                },
                {
                    name: '实时到位价差值',
                    nameLocation: 'end', // 单位的位置，放在轴的末端
                    type: 'bar',
                    data: seriesData1, // y 轴数据
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0,0,0,0.3)'
                        }
                    },
                    // barGap: '100%',
                    barWidth: '20px',
                    label: {
                        show: true,
                        position: 'bottom',
                        formatter: params => {
                            const diffClass = params.value > 0 ? 'positive' : 'negative'
                            return ` {${diffClass}|${params.value}}`
                        },
                        rich: {
                            a: { color: '#000' }, // 默认的文本颜色
                            positive: { color: 'green' }, // 正数的颜色
                            negative: { color: 'red' } // 负数的颜色
                        }
                    }
                }
            ],
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
                // formatter: function (params) {
                //     var historyDiff = params[0].value // 历史到位价差值
                //     var realTimeDiff = params[1].value // 实时到位价差值
                //     var unit = '元/吨' // 单位
                //
                //     return (
                //         params[0].name +
                //         '<br/>' +
                //         '历史到位价差值: ' +
                //         historyDiff +
                //         ' ' +
                //         unit +
                //         '<br/>' +
                //         '实时到位价差值: ' +
                //         realTimeDiff +
                //         ' ' +
                //         unit
                //     )
                // }
            }
        }
    }

    // 渲染图表函数
    const renderChart = () => {
        if (state.dynamicData.length > 0) {
            echarts.dispose(chartContainer.value)
            echarts.dispose(rightContauner.value)
            myChart = echarts.init(chartContainer.value)
            rightChart = echarts.init(rightContauner.value)
            const option = getOptionFromData(state.dynamicData)
            const rightOption = getRightOptionFromData(state.dynamicData)
            option && myChart.setOption(option)
            rightOption && rightChart.setOption(rightOption)
        } else {
            echarts.dispose(chartContainer.value)
            echarts.dispose(rightContauner.value)
        }
    }

    onMounted(async () => {
        const urlParams = new URLSearchParams(window.location.search)

        // 获取单个参数
        state.urlRegionId = Number(urlParams.get('regionId'))
        await getCountryTreeList(true)
        await nextTick()
        // 初始化 ECharts 实例
        myChart = echarts.init(chartContainer.value)
        rightChart = echarts.init(rightContauner.value)
        // 监听窗口尺寸变化
        window.addEventListener('resize', handleResize)
    })

    const handleResize = () => {
        if (myChart) {
            myChart.resize()
        }
        if (rightChart) {
            rightChart.resize()
        }
    }

    // 组件卸载时移除 resize 监听器
    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize)
    })
    const columns = [
        {
            title: '序号',
            align: 'center',
            dataIndex: 'count'
        },
        {
            title: '区域',
            align: 'center',
            dataIndex: 'areaName'
        },
        {
            title: '近1年平均到位价(元/吨)',
            align: 'center',
            dataIndex: 'yearInplacePrice'
        },
        {
            title: '当前到位价(元/吨)',
            align: 'center',
            dataIndex: 'inplacePrice'
        },
        {
            title: '近1年平均到位价差(元/吨)',
            align: 'center',
            dataIndex: 'yearInplacePriceDifference'
        },
        {
            title: '当前到位价差(元/吨)',
            align: 'center',
            dataIndex: 'inplacePriceDifference'
        }
    ]
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .vid_alrw8ri7qx :deep(a) {
        color: undefined;
    }
    :deep(.vid_alrw8ri7qx.@{ant-prefix}-breadcrumb) > span:last-child a {
        color: undefined;
        opacity: 0.75;
    }
    .vid_alrw8ri7qx {
        height: 40px;
        display: flex;
        align-items: center;
        flex-wrap: undefined;
        margin-bottom: 24px;
        padding-right: 24px;
        padding-left: 24px;
        background-color: #ffffff;
    }

    .body {
        padding: 0 24px;
    }
    .page_root {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
    .top-search {
        height: 68px;
        background-color: #fff;
        padding: 16px 24px;
        border-radius: 4px;
        margin-bottom: 16px;
    }
    .content {
        background-color: #fff;
        border-radius: 4px;
        padding: 24px;
        padding-top: 24px;
        height: calc(100vh - 180px);
        overflow: auto;
        padding-bottom: 8px;
    }
    .top-chart {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
    }
    .left {
        width: 55%;
        box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
        height: 100%;
    }
    .right {
        flex: 1;
        box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
        height: 100%;
    }
    /*表格按钮通用样式*/
    .default-table :deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #f5f5f5;
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 600;
        color: #262626;
        padding: 8px 16px;
    }
    .default-table :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #595959;
        border-bottom: 1px solid #d9d9d9;
        padding: 6px 16px;
        word-break: break-all;
    }
    /*表格按钮通用样式*/
    .content-title {
        padding: 10px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .tip {
        height: 40px;
        display: flex;
        line-height: 20px;
        align-items: center;
    }
    .tip-msg {
        height: 20px;
        font-size: 16px;
        line-height: 20px;
        font-weight: 600;
    }
    /*表格顶部的标题*/
    .chart {
        height: 300px;
        position: relative;
    }
    .money-content {
        position: absolute;
        left: 75%;
        top: 150%;
        width: 200px;
        height: 30px;
        z-index: 999;
    }
    .flag {
        position: relative;
    }
</style>
